const axios = require('axios');
const RSSParser = require('rss-parser');

class AIService {
  constructor() {
    this.apiKey = null;
    this.apiProvider = 'openai'; // openai, claude, wenxin, openrouter
    this.baseURL = 'https://api.openai.com/v1';
    this.model = null; // 用于指定具体模型，如DeepSeek
    this.rssParser = new RSSParser();
    
    // 技术资讯源
    this.techNewsFeeds = [
      'https://www.infoq.cn/feed',
      'https://www.oschina.net/news/rss'
    ];
  }

  setApiConfig(provider, apiKey, baseURL = null, model = null) {
    this.apiProvider = provider;
    this.apiKey = apiKey;
    this.model = model;
    
    switch (provider) {
      case 'openai':
        this.baseURL = baseURL || 'https://api.openai.com/v1';
        this.model = model || 'gpt-3.5-turbo';
        break;
      case 'claude':
        this.baseURL = baseURL || 'https://api.anthropic.com/v1';
        this.model = model || 'claude-3-sonnet-20240229';
        break;
      case 'wenxin':
        this.baseURL = baseURL || 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop';
        break;
      case 'openrouter':
        this.baseURL = baseURL || 'https://openrouter.ai/api/v1';
        this.model = model || 'deepseek/deepseek-chat';
        break;
    }
  }

  async generateTopics(preferences = {}) {
    try {
      // 获取热点话题
      const hotTopics = await this.getHotTopics();
      
      // 基于用户偏好生成主题
      const prompt = this.buildTopicPrompt(preferences, hotTopics);
      const response = await this.callAI(prompt, { maxTokens: 500 });
      
      return this.parseTopics(response);
    } catch (error) {
      console.error('生成主题失败:', error);
      throw new Error('生成主题失败，请检查网络连接和API配置');
    }
  }

  async generateArticle(topic, options = {}) {
    try {
      const {
        length = 'normal',     // short, normal, long
        style = 'professional', // accessible, professional, humorous
        keywords = [],
        includeCode = true
      } = options;

      const prompt = this.buildArticlePrompt(topic, length, style, keywords, includeCode);
      
      const response = await this.callAI(prompt, { 
        maxTokens: this.getMaxTokensByLength(length),
        temperature: style === 'humorous' ? 0.8 : 0.7
      });

      return {
        title: this.extractTitle(response),
        content: this.formatContent(response),
        wordCount: this.countWords(response),
        generatedAt: new Date().toISOString()
      };
    } catch (error) {
      console.error('生成文章失败:', error);
      throw new Error('生成文章失败，请检查网络连接和API配置');
    }
  }

  async getHotTopics() {
    const topics = [];
    
    for (const feedUrl of this.techNewsFeeds) {
      try {
        const feed = await this.rssParser.parseURL(feedUrl);
        const recentItems = feed.items.slice(0, 5).map(item => ({
          title: item.title,
          link: item.link,
          pubDate: item.pubDate
        }));
        topics.push(...recentItems);
      } catch (error) {
        console.warn(`获取RSS源失败: ${feedUrl}`, error);
      }
    }
    
    return topics.slice(0, 10); // 返回最新的10个话题
  }

  buildTopicPrompt(preferences, hotTopics) {
    const hotTopicsText = hotTopics.map(topic => `- ${topic.title}`).join('\n');
    
    return `作为一个技术内容专家，请基于以下信息生成5个适合技术公众号的文章主题：

用户偏好：
- 技术领域：${preferences.techFields || '前端开发、后端开发、人工智能、云计算'}
- 难度级别：${preferences.difficulty || '中级'}
- 关注点：${preferences.interests || '新技术趋势、最佳实践、性能优化'}

当前热点话题：
${hotTopicsText}

请生成5个具体的技术文章主题，每个主题应该：
1. 具有实用价值和技术深度
2. 适合公众号读者阅读
3. 包含具体的技术点或解决方案
4. 标题吸引人且准确

格式：
1. [主题标题]
2. [主题标题]
...`;
  }

  buildArticlePrompt(topic, length, style, keywords, includeCode) {
    const lengthGuide = {
      short: '800-1200字',
      normal: '1500-2500字',
      long: '3000-5000字'
    };

    const styleGuide = {
      accessible: '通俗易懂，避免过多专业术语，多用比喻和例子',
      professional: '专业严谨，逻辑清晰，术语准确',
      humorous: '轻松幽默，适当使用网络用语和段子'
    };

    const keywordsText = keywords.length > 0 ? `\n必须包含关键词：${keywords.join('、')}` : '';
    const codeRequirement = includeCode ? '\n- 包含实用的代码示例，代码需要完整可运行' : '';

    return `请写一篇关于"${topic}"的技术文章。

要求：
- 字数：${lengthGuide[length]}
- 写作风格：${styleGuide[style]}
- 结构：引言 -> 正文（分点论述）-> 总结${keywordsText}${codeRequirement}

文章结构要求：
1. 吸引人的开头，说明问题的重要性
2. 正文分为3-5个部分，每部分有明确的小标题
3. 每个部分包含具体的技术解释和实例
4. 如需代码示例，请使用适当的编程语言
5. 结尾总结要点并提供进一步学习建议

请确保内容技术准确，避免错误信息。`;
  }

  async callAI(prompt, options = {}) {
    const { maxTokens = 2000, temperature = 0.7 } = options;

    if (!this.apiKey) {
      throw new Error('请先配置API密钥');
    }

    let requestConfig;

    switch (this.apiProvider) {
      case 'openai':
        requestConfig = {
          url: `${this.baseURL}/chat/completions`,
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json'
          },
          data: {
            model: this.model,
            messages: [{ role: 'user', content: prompt }],
            max_tokens: maxTokens,
            temperature: temperature
          }
        };
        break;

      case 'openrouter':
        requestConfig = {
          url: `${this.baseURL}/chat/completions`,
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json',
            'HTTP-Referer': 'https://ai2word.app',
            'X-Title': 'AI2Word'
          },
          data: {
            model: this.model,
            messages: [{ role: 'user', content: prompt }],
            max_tokens: maxTokens,
            temperature: temperature
          }
        };
        break;

      case 'claude':
        requestConfig = {
          url: `${this.baseURL}/messages`,
          method: 'POST',
          headers: {
            'x-api-key': this.apiKey,
            'Content-Type': 'application/json',
            'anthropic-version': '2023-06-01'
          },
          data: {
            model: this.model,
            max_tokens: maxTokens,
            messages: [{ role: 'user', content: prompt }]
          }
        };
        break;

      default:
        throw new Error(`不支持的AI提供商: ${this.apiProvider}`);
    }

    const response = await axios(requestConfig);
    
    if (this.apiProvider === 'openai' || this.apiProvider === 'openrouter') {
      return response.data.choices[0].message.content;
    } else if (this.apiProvider === 'claude') {
      return response.data.content[0].text;
    }
  }

  parseTopics(response) {
    const lines = response.split('\n').filter(line => line.trim());
    const topics = [];
    
    for (const line of lines) {
      const match = line.match(/^\d+\.\s*(.+)$/);
      if (match) {
        topics.push({
          title: match[1].trim(),
          id: Date.now() + Math.random(),
          createdAt: new Date().toISOString()
        });
      }
    }
    
    return topics;
  }

  extractTitle(content) {
    const lines = content.split('\n');
    for (const line of lines) {
      const trimmed = line.trim();
      if (trimmed && !trimmed.startsWith('#')) {
        return trimmed;
      }
      if (trimmed.startsWith('# ')) {
        return trimmed.substring(2);
      }
    }
    return '技术文章';
  }

  formatContent(content) {
    // 基础格式化：确保标题、段落、代码块格式正确
    return content
      .replace(/^#+\s*/gm, '') // 移除markdown标题符号
      .replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
        return `<pre><code class="language-${lang || 'text'}">${code.trim()}</code></pre>`;
      })
      .replace(/`([^`]+)`/g, '<code>$1</code>')
      .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
      .replace(/\*([^*]+)\*/g, '<em>$1</em>')
      .split('\n\n')
      .map(paragraph => paragraph.trim() ? `<p>${paragraph.trim()}</p>` : '')
      .join('\n');
  }

  countWords(text) {
    // 简单的中文字符计数
    return text.replace(/[^\u4e00-\u9fa5]/g, '').length;
  }

  getMaxTokensByLength(length) {
    const tokenMap = {
      short: 1500,
      normal: 3000,
      long: 5000
    };
    return tokenMap[length] || 3000;
  }
}

module.exports = AIService;